import { createRouter, createWebHashHistory } from 'vue-router'
import { staticRoutes } from '@/router/data'
import useUserStore from '@/stores/user'
import useRoutesStore from '@/stores/routes'
import Layout from '@/commom/components/layouts/Layout.vue'
const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHashHistory(),
  routes: staticRoutes
})

//设置白名单不过路由守卫
const routesWhiteList = ['/404', '/403', '/login']

//路由守卫检查
router.beforeEach(async (to, from, next) => {
  if (routesWhiteList.includes(to.path)) {
    next()
  } else {
    const userStore = useUserStore()
    const routesStore = useRoutesStore()
    if (userStore.userInfo.id && userStore.userInfo.username && routesStore.routeList.length > 0) {
      next()
    } else {
      try {
        await userStore.setUserInfo()
        await routesStore.setMenus()
        await routesStore.setRouteList(routesStore.menuList)
        const routeList = routesStore.routeList
        // debugger
        router.addRoute({
          component: Layout,
          path: '/',
          redirect: 'home/index',
          children: routeList
        })
        next({ ...to })
      } catch {
        next({ path: '/login', replace: true })
      }
    }
  }
})

export default router
